import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "motion/react";
import { Button } from "./ui/button";
import { Card } from "./ui/card";
import { Badge } from "./ui/badge";
import { Dialog, DialogContent, DialogTrigger, DialogTitle, DialogDescription } from "./ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import { Switch } from "./ui/switch";
import {
  Settings,
  Plus,
  Trash2,
  Play,
  Square,
  RefreshCw,
  AlertCircle,
  CheckCircle,
  ExternalLink,
  Copy,
  Eye,
  EyeOff
} from "lucide-react";

// 类型定义
export interface ExtensionConfig {
  id: string;
  name: string;
  type: 'stdio' | 'sse' | 'builtin' | 'streamable_http' | 'frontend';
  description?: string;
  enabled: boolean;
  bundled?: boolean;
  // stdio 类型
  cmd?: string;
  args?: string[];
  // sse/http 类型
  uri?: string;
  headers?: Record<string, string>;
  // 通用
  envs?: Record<string, string>;
  env_keys?: string[];
  timeout?: number;
  // 状态
  status?: 'connected' | 'disconnected' | 'error' | 'connecting';
  error?: string;
}

export interface McpTool {
  name: string;
  description: string;
  input_schema: any;
  service_id?: string;
}

interface ExtensionsPanelProps {
  isOpen: boolean;
  onClose: () => void;
  extensions: ExtensionConfig[];
  tools: McpTool[];
  onExtensionCreate: (extension: Partial<ExtensionConfig>) => Promise<void>;
  onExtensionUpdate: (id: string, updates: Partial<ExtensionConfig>) => Promise<void>;
  onExtensionDelete: (id: string) => Promise<void>;
  onExtensionToggle: (id: string, enabled: boolean) => Promise<void>;
  onToolExecute: (toolName: string, params: any) => Promise<any>;
}

export function ExtensionsPanel({
  isOpen,
  onClose,
  extensions,
  tools,
  onExtensionCreate,
  onExtensionUpdate,
  onExtensionDelete,
  onExtensionToggle,
  onToolExecute,
}: ExtensionsPanelProps) {
  const [activeTab, setActiveTab] = useState<'extensions' | 'tools'>('extensions');
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [editingExtension, setEditingExtension] = useState<ExtensionConfig | null>(null);
  const [newExtension, setNewExtension] = useState<Partial<ExtensionConfig>>({
    type: 'stdio',
    enabled: true,
    envs: {},
    headers: {},
  });
  const [executingTool, setExecutingTool] = useState<string | null>(null);
  const [toolResults, setToolResults] = useState<Record<string, any>>({});
  const [showEnvVars, setShowEnvVars] = useState<Record<string, boolean>>({});

  // 重置表单
  const resetForm = () => {
    setNewExtension({
      type: 'stdio',
      enabled: true,
      envs: {},
      headers: {},
    });
    setEditingExtension(null);
  };

  // 处理创建扩展
  const handleCreateExtension = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newExtension.name) return;

    try {
      await onExtensionCreate(newExtension);
      setShowCreateDialog(false);
      resetForm();
    } catch (error) {
      console.error('Failed to create extension:', error);
    }
  };

  // 处理更新扩展
  const handleUpdateExtension = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingExtension) return;

    try {
      await onExtensionUpdate(editingExtension.id, newExtension);
      setEditingExtension(null);
      resetForm();
    } catch (error) {
      console.error('Failed to update extension:', error);
    }
  };

  // 处理工具执行
  const handleToolExecute = async (toolName: string) => {
    setExecutingTool(toolName);
    try {
      const result = await onToolExecute(toolName, {});
      setToolResults(prev => ({ ...prev, [toolName]: result }));
    } catch (error) {
      setToolResults(prev => ({
        ...prev,
        [toolName]: { error: (error as Error).message }
      }));
    } finally {
      setExecutingTool(null);
    }
  };

  // 开始编辑扩展
  const startEditExtension = (extension: ExtensionConfig) => {
    setEditingExtension(extension);
    setNewExtension({
      name: extension.name,
      type: extension.type,
      description: extension.description,
      cmd: extension.cmd,
      args: extension.args,
      uri: extension.uri,
      envs: extension.envs || {},
      headers: extension.headers || {},
      timeout: extension.timeout,
      enabled: extension.enabled,
    });
    setShowCreateDialog(true);
  };

  // 获取扩展状态图标
  const getStatusIcon = (status?: string) => {
    switch (status) {
      case 'connected':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'error':
        return <AlertCircle className="w-4 h-4 text-red-500" />;
      case 'connecting':
        return <RefreshCw className="w-4 h-4 text-yellow-500 animate-spin" />;
      default:
        return <AlertCircle className="w-4 h-4 text-gray-500" />;
    }
  };

  // 渲染环境变量编辑器
  const renderEnvEditor = (envs: Record<string, string>, onChange: (envs: Record<string, string>) => void) => {
    const envEntries = Object.entries(envs || {});

    return (
      <div className="space-y-3">
        {envEntries.length === 0 ? (
          <div className="text-center py-4 text-slate-500 dark:text-slate-400 text-sm">
            暂无环境变量，点击下方按钮添加
          </div>
        ) : (
          envEntries.map(([key, value], index) => (
            <motion.div 
              key={index} 
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              className="flex gap-3 p-3 bg-white dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-700"
            >
              <div className="flex-1">
                <Label className="text-xs text-slate-500 dark:text-slate-400 mb-1 block">变量名</Label>
                <Input
                  placeholder="例如: API_KEY"
                  value={key}
                  onChange={(e) => {
                    const newEnvs = { ...envs };
                    delete newEnvs[key];
                    newEnvs[e.target.value] = value;
                    onChange(newEnvs);
                  }}
                  className="font-mono text-sm"
                />
              </div>
              <div className="flex-1">
                <Label className="text-xs text-slate-500 dark:text-slate-400 mb-1 block">变量值</Label>
                <div className="relative">
                  <Input
                    type={showEnvVars[key] ? "text" : "password"}
                    placeholder="变量值"
                    value={value}
                    onChange={(e) => {
                      onChange({ ...envs, [key]: e.target.value });
                    }}
                    className="font-mono text-sm pr-8"
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="absolute right-1 top-1 h-6 w-6 p-0 hover:bg-slate-100 dark:hover:bg-slate-800"
                    onClick={() => setShowEnvVars(prev => ({ ...prev, [key]: !prev[key] }))}
                  >
                    {showEnvVars[key] ? <EyeOff className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
                  </Button>
                </div>
              </div>
              <div className="flex items-end">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    const newEnvs = { ...envs };
                    delete newEnvs[key];
                    onChange(newEnvs);
                  }}
                  className="hover:bg-red-50 hover:border-red-200 hover:text-red-600 dark:hover:bg-red-900/20 dark:hover:border-red-800 dark:hover:text-red-400"
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
            </motion.div>
          ))
        )}
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={() => onChange({ ...envs, '': '' })}
          className="w-full border-dashed hover:bg-purple-50 hover:border-purple-300 dark:hover:bg-purple-900/20 dark:hover:border-purple-700"
        >
          <Plus className="w-4 h-4 mr-2" />
          添加环境变量
        </Button>
      </div>
    );
  };

  if (!isOpen) return null;

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black/60 backdrop-blur-md z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.9, opacity: 0, y: 20 }}
        animate={{ scale: 1, opacity: 1, y: 0 }}
        exit={{ scale: 0.9, opacity: 0, y: 20 }}
        transition={{ type: "spring", damping: 25, stiffness: 300 }}
        className="bg-white dark:bg-slate-900 rounded-2xl shadow-2xl border border-slate-200/50 dark:border-slate-700/50 w-full max-w-7xl h-[85vh] flex flex-col overflow-hidden backdrop-blur-xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 bg-gradient-to-r from-blue-50 to-purple-50 dark:from-slate-800 dark:to-slate-800 border-b border-slate-200/50 dark:border-slate-700/50">
          <div className="flex items-center gap-4">
            <div className="p-2 bg-blue-500/10 dark:bg-blue-500/20 rounded-xl">
              <Settings className="w-6 h-6 text-blue-600 dark:text-blue-400" />
            </div>
            <div>
              <h2 className="text-2xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
                扩展管理
              </h2>
              <p className="text-sm text-slate-600 dark:text-slate-400 mt-1">
                管理 MCP 扩展和工具，配置您的 AI 助手能力
              </p>
            </div>
          </div>
          <Button 
            variant="outline" 
            onClick={onClose}
            className="hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
          >
            关闭
          </Button>
        </div>

        {/* 标签页 */}
        <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as any)} className="flex-1 flex flex-col">
          <div className="px-6 pt-4 pb-2">
            <TabsList className="grid w-full grid-cols-2 bg-slate-100 dark:bg-slate-800 p-1 rounded-xl">
              <TabsTrigger 
                value="extensions" 
                className="data-[state=active]:bg-white dark:data-[state=active]:bg-slate-700 data-[state=active]:shadow-sm transition-all duration-200"
              >
                <Settings className="w-4 h-4 mr-2" />
                扩展服务
              </TabsTrigger>
              <TabsTrigger 
                value="tools"
                className="data-[state=active]:bg-white dark:data-[state=active]:bg-slate-700 data-[state=active]:shadow-sm transition-all duration-200"
              >
                <Play className="w-4 h-4 mr-2" />
                可用工具
              </TabsTrigger>
            </TabsList>
          </div>

          {/* 扩展管理 */}
          <TabsContent value="extensions" className="flex-1 p-6 pt-2 overflow-hidden">
            <div className="flex justify-between items-center mb-6">
              <div>
                <h3 className="text-xl font-semibold text-slate-900 dark:text-white">MCP 扩展服务</h3>
                <p className="text-sm text-slate-500 dark:text-slate-400 mt-1">
                  管理您的模型上下文协议扩展
                </p>
              </div>
              <Button 
                onClick={() => setShowCreateDialog(true)}
                className="bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600 text-white shadow-lg hover:shadow-xl transition-all duration-200"
              >
                <Plus className="w-4 h-4 mr-2" />
                添加扩展
              </Button>
            </div>

            <div className="grid gap-4 max-h-[calc(100vh-300px)] overflow-y-auto pr-2 chat-scrollbar">
              {extensions.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-12 text-center">
                  <div className="w-16 h-16 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mb-4">
                    <Settings className="w-8 h-8 text-slate-400" />
                  </div>
                  <h4 className="text-lg font-medium text-slate-900 dark:text-white mb-2">
                    暂无扩展服务
                  </h4>
                  <p className="text-slate-500 dark:text-slate-400 mb-4 max-w-md">
                    添加 MCP 扩展来增强您的 AI 助手能力，支持文件操作、网络请求等功能
                  </p>
                  <Button 
                    onClick={() => setShowCreateDialog(true)}
                    variant="outline"
                    className="border-dashed"
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    添加第一个扩展
                  </Button>
                </div>
              ) : (
                extensions.map((extension) => (
                  <motion.div
                    key={extension.id}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.2 }}
                    whileHover={{ y: -2 }}
                  >
                    <Card className="p-5 hover:shadow-lg hover:shadow-blue-500/10 transition-all duration-300 border-slate-200/60 dark:border-slate-700/60 bg-gradient-to-br from-white to-slate-50/50 dark:from-slate-900 dark:to-slate-800/50 hover:border-blue-300/50 dark:hover:border-blue-700/50">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-3 mb-3">
                            <div className="relative">
                              {getStatusIcon(extension.status)}
                              {extension.status === 'connected' && (
                                <div className="absolute -top-1 -right-1 w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
                              )}
                            </div>
                            <h4 className="font-semibold text-slate-900 dark:text-white text-lg">
                              {extension.name}
                            </h4>
                            <Badge 
                              variant={extension.enabled ? "default" : "secondary"}
                              className={`${extension.enabled 
                                ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' 
                                : 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400'
                              }`}
                            >
                              {extension.type.toUpperCase()}
                            </Badge>
                            {extension.bundled && (
                              <Badge variant="outline" className="border-blue-200 text-blue-600 dark:border-blue-800 dark:text-blue-400">
                                <CheckCircle className="w-3 h-3 mr-1" />
                                内置
                              </Badge>
                            )}
                          </div>

                          {extension.description && (
                            <p className="text-sm text-slate-600 dark:text-slate-400 mb-3 leading-relaxed">
                              {extension.description}
                            </p>
                          )}

                          <div className="flex items-center gap-4 text-xs text-slate-500 dark:text-slate-500">
                            {extension.type === 'stdio' && extension.cmd && (
                              <div className="flex items-center gap-1 bg-slate-100 dark:bg-slate-800 px-2 py-1 rounded">
                                <span className="font-mono">命令:</span>
                                <span className="font-mono text-slate-700 dark:text-slate-300">{extension.cmd}</span>
                              </div>
                            )}
                            {(extension.type === 'sse' || extension.type === 'streamable_http') && extension.uri && (
                              <div className="flex items-center gap-1 bg-slate-100 dark:bg-slate-800 px-2 py-1 rounded">
                                <ExternalLink className="w-3 h-3" />
                                <span className="font-mono text-slate-700 dark:text-slate-300">{extension.uri}</span>
                              </div>
                            )}
                          </div>

                          {extension.error && (
                            <motion.div 
                              initial={{ opacity: 0, height: 0 }}
                              animate={{ opacity: 1, height: 'auto' }}
                              className="mt-3 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg"
                            >
                              <div className="flex items-center gap-2 text-sm text-red-600 dark:text-red-400">
                                <AlertCircle className="w-4 h-4" />
                                <span className="font-medium">错误:</span>
                                <span>{extension.error}</span>
                              </div>
                            </motion.div>
                          )}
                        </div>

                        <div className="flex items-center gap-3 ml-4">
                          <div className="flex items-center gap-2">
                            <span className="text-xs text-slate-500 dark:text-slate-400">
                              {extension.enabled ? '已启用' : '已禁用'}
                            </span>
                            <Switch
                              checked={extension.enabled}
                              onCheckedChange={(enabled) => onExtensionToggle(extension.id, enabled)}
                            />
                          </div>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => startEditExtension(extension)}
                            className="hover:bg-blue-50 hover:border-blue-200 dark:hover:bg-blue-900/20 dark:hover:border-blue-800"
                          >
                            编辑
                          </Button>
                          {!extension.bundled && (
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => onExtensionDelete(extension.id)}
                              className="hover:bg-red-50 hover:border-red-200 hover:text-red-600 dark:hover:bg-red-900/20 dark:hover:border-red-800 dark:hover:text-red-400"
                            >
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          )}
                        </div>
                      </div>
                    </Card>
                  </motion.div>
                ))
              )}
            </div>
          </TabsContent>

          {/* 工具管理 */}
          <TabsContent value="tools" className="flex-1 p-6 pt-2 overflow-hidden">
            <div className="mb-6">
              <h3 className="text-xl font-semibold text-slate-900 dark:text-white">可用工具</h3>
              <p className="text-sm text-slate-500 dark:text-slate-400 mt-1">
                来自已连接扩展的工具，点击测试按钮验证功能
              </p>
            </div>

            <div className="grid gap-4 max-h-[calc(100vh-300px)] overflow-y-auto pr-2 chat-scrollbar">
              {tools.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-12 text-center">
                  <div className="w-16 h-16 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mb-4">
                    <Play className="w-8 h-8 text-slate-400" />
                  </div>
                  <h4 className="text-lg font-medium text-slate-900 dark:text-white mb-2">
                    暂无可用工具
                  </h4>
                  <p className="text-slate-500 dark:text-slate-400 mb-4 max-w-md">
                    工具来自已连接的扩展服务。请先添加并启用扩展服务以获取可用工具。
                  </p>
                  <Button 
                    onClick={() => setActiveTab('extensions')}
                    variant="outline"
                  >
                    <Settings className="w-4 h-4 mr-2" />
                    管理扩展
                  </Button>
                </div>
              ) : (
                tools.map((tool) => (
                  <motion.div
                    key={tool.name}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.2 }}
                    whileHover={{ y: -2 }}
                  >
                    <Card className="p-5 hover:shadow-lg hover:shadow-green-500/10 transition-all duration-300 border-slate-200/60 dark:border-slate-700/60 bg-gradient-to-br from-white to-slate-50/50 dark:from-slate-900 dark:to-slate-800/50 hover:border-green-300/50 dark:hover:border-green-700/50">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-3 mb-2">
                            <div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
                              <Play className="w-4 h-4 text-blue-600 dark:text-blue-400" />
                            </div>
                            <h4 className="font-semibold text-slate-900 dark:text-white text-lg">
                              {tool.name}
                            </h4>
                            {tool.service_id && (
                              <Badge variant="outline" className="text-xs border-purple-200 text-purple-600 dark:border-purple-800 dark:text-purple-400">
                                {tool.service_id}
                              </Badge>
                            )}
                          </div>
                          
                          <p className="text-sm text-slate-600 dark:text-slate-400 mb-3 leading-relaxed">
                            {tool.description}
                          </p>

                          {tool.input_schema && (
                            <div className="text-xs text-slate-500 dark:text-slate-500">
                              <span className="font-medium">输入参数:</span>
                              <span className="ml-2 font-mono bg-slate-100 dark:bg-slate-800 px-2 py-1 rounded">
                                {Object.keys(tool.input_schema.properties || {}).join(', ') || '无'}
                              </span>
                            </div>
                          )}
                        </div>

                        <div className="flex items-center gap-2 ml-4">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleToolExecute(tool.name)}
                            disabled={executingTool === tool.name}
                            className={`${
                              executingTool === tool.name 
                                ? 'bg-yellow-50 border-yellow-200 text-yellow-700 dark:bg-yellow-900/20 dark:border-yellow-800 dark:text-yellow-400' 
                                : 'hover:bg-green-50 hover:border-green-200 hover:text-green-700 dark:hover:bg-green-900/20 dark:hover:border-green-800 dark:hover:text-green-400'
                            }`}
                          >
                            {executingTool === tool.name ? (
                              <>
                                <RefreshCw className="w-4 h-4 animate-spin mr-2" />
                                执行中
                              </>
                            ) : (
                              <>
                                <Play className="w-4 h-4 mr-2" />
                                测试
                              </>
                            )}
                          </Button>
                        </div>
                      </div>

                      {/* 工具执行结果 */}
                      <AnimatePresence>
                        {toolResults[tool.name] && (
                          <motion.div 
                            initial={{ opacity: 0, height: 0 }}
                            animate={{ opacity: 1, height: 'auto' }}
                            exit={{ opacity: 0, height: 0 }}
                            className="mt-4 p-4 bg-slate-50 dark:bg-slate-800 rounded-lg border border-slate-200 dark:border-slate-700"
                          >
                            <div className="flex items-center justify-between mb-3">
                              <div className="flex items-center gap-2">
                                <CheckCircle className="w-4 h-4 text-green-500" />
                                <span className="text-sm font-medium text-slate-900 dark:text-white">执行结果</span>
                              </div>
                              <div className="flex items-center gap-2">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => {
                                    navigator.clipboard.writeText(JSON.stringify(toolResults[tool.name], null, 2));
                                  }}
                                  className="h-6 px-2 text-xs"
                                >
                                  <Copy className="w-3 h-3 mr-1" />
                                  复制
                                </Button>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => {
                                    const newResults = { ...toolResults };
                                    delete newResults[tool.name];
                                    setToolResults(newResults);
                                  }}
                                  className="h-6 px-2 text-xs"
                                >
                                  关闭
                                </Button>
                              </div>
                            </div>
                            <pre className="text-xs bg-white dark:bg-slate-900 p-3 rounded border overflow-x-auto font-mono leading-relaxed">
                              {JSON.stringify(toolResults[tool.name], null, 2)}
                            </pre>
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </Card>
                  </motion.div>
                ))
              )}
            </div>
          </TabsContent>
        </Tabs>

        {/* 创建/编辑扩展对话框 */}
        <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
          <DialogContent className="max-w-3xl max-h-[85vh] overflow-y-auto">
            <div className="flex items-center gap-3 mb-4">
              <div className="p-2 bg-blue-500/10 dark:bg-blue-500/20 rounded-xl">
                <Settings className="w-5 h-5 text-blue-600 dark:text-blue-400" />
              </div>
              <div>
                <DialogTitle className="text-xl font-semibold">
                  {editingExtension ? '编辑扩展' : '添加新扩展'}
                </DialogTitle>
                <DialogDescription className="text-slate-600 dark:text-slate-400">
                  配置 MCP 扩展服务以增强 AI 助手能力
                </DialogDescription>
              </div>
            </div>

            <form onSubmit={editingExtension ? handleUpdateExtension : handleCreateExtension} className="space-y-6">
              {/* 基本信息 */}
              <div className="bg-slate-50 dark:bg-slate-800/50 p-4 rounded-xl">
                <h4 className="font-medium text-slate-900 dark:text-white mb-3">基本信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="name" className="text-sm font-medium">扩展名称 *</Label>
                    <Input
                      id="name"
                      value={newExtension.name || ''}
                      onChange={(e) => setNewExtension(prev => ({ ...prev, name: e.target.value }))}
                      placeholder="例如: file-manager"
                      required
                      className="mt-1"
                    />
                  </div>
                  <div>
                    <Label htmlFor="type" className="text-sm font-medium">扩展类型 *</Label>
                    <select
                      id="type"
                      value={newExtension.type}
                      onChange={(e) => setNewExtension(prev => ({ ...prev, type: e.target.value as any }))}
                      className="w-full px-3 py-2 mt-1 border border-slate-300 dark:border-slate-600 rounded-md bg-white dark:bg-slate-800 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    >
                      <option value="stdio">Stdio (标准输入输出)</option>
                      <option value="sse">SSE (服务器发送事件)</option>
                      <option value="streamable_http">HTTP (HTTP 服务)</option>
                      <option value="builtin">Builtin (内置扩展)</option>
                    </select>
                  </div>
                </div>
                
                <div className="mt-4">
                  <Label htmlFor="description" className="text-sm font-medium">描述</Label>
                  <Textarea
                    id="description"
                    value={newExtension.description || ''}
                    onChange={(e) => setNewExtension(prev => ({ ...prev, description: e.target.value }))}
                    placeholder="描述此扩展的功能和用途..."
                    className="mt-1 resize-none"
                    rows={3}
                  />
                </div>
              </div>

              {/* 根据类型显示不同的配置选项 */}
              {newExtension.type === 'stdio' && (
                <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-xl border border-blue-200 dark:border-blue-800">
                  <h4 className="font-medium text-blue-900 dark:text-blue-100 mb-3 flex items-center gap-2">
                    <Square className="w-4 h-4" />
                    Stdio 配置
                  </h4>
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="cmd" className="text-sm font-medium">执行命令 *</Label>
                      <Input
                        id="cmd"
                        value={newExtension.cmd || ''}
                        onChange={(e) => setNewExtension(prev => ({ ...prev, cmd: e.target.value }))}
                        placeholder="例如: python, node, uvx"
                        className="mt-1 font-mono"
                      />
                    </div>
                    <div>
                      <Label htmlFor="args" className="text-sm font-medium">命令参数 (每行一个)</Label>
                      <Textarea
                        id="args"
                        value={newExtension.args?.join('\n') || ''}
                        onChange={(e) => setNewExtension(prev => ({
                          ...prev,
                          args: e.target.value.split('\n').filter(Boolean)
                        }))}
                        placeholder="例如:&#10;script.py&#10;--verbose&#10;--config=config.json"
                        className="mt-1 font-mono resize-none"
                        rows={4}
                      />
                    </div>
                  </div>
                </div>
              )}

              {(newExtension.type === 'sse' || newExtension.type === 'streamable_http') && (
                <div className="bg-green-50 dark:bg-green-900/20 p-4 rounded-xl border border-green-200 dark:border-green-800">
                  <h4 className="font-medium text-green-900 dark:text-green-100 mb-3 flex items-center gap-2">
                    <ExternalLink className="w-4 h-4" />
                    网络配置
                  </h4>
                  <div>
                    <Label htmlFor="uri" className="text-sm font-medium">服务 URI *</Label>
                    <Input
                      id="uri"
                      value={newExtension.uri || ''}
                      onChange={(e) => setNewExtension(prev => ({ ...prev, uri: e.target.value }))}
                      placeholder="例如: http://localhost:3000/mcp 或 ws://localhost:3000"
                      className="mt-1 font-mono"
                    />
                  </div>
                </div>
              )}

              {/* 环境变量配置 */}
              <div className="bg-purple-50 dark:bg-purple-900/20 p-4 rounded-xl border border-purple-200 dark:border-purple-800">
                <h4 className="font-medium text-purple-900 dark:text-purple-100 mb-3 flex items-center gap-2">
                  <Settings className="w-4 h-4" />
                  环境变量
                </h4>
                {renderEnvEditor(
                  newExtension.envs || {},
                  (envs) => setNewExtension(prev => ({ ...prev, envs }))
                )}
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-end gap-3 pt-4 border-t border-slate-200 dark:border-slate-700">
                <Button 
                  type="button" 
                  variant="outline" 
                  onClick={() => {
                    setShowCreateDialog(false);
                    resetForm();
                  }}
                  className="px-6"
                >
                  取消
                </Button>
                <Button 
                  type="submit"
                  className="px-6 bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600 text-white"
                >
                  {editingExtension ? '更新扩展' : '创建扩展'}
                </Button>
              </div>
            </form>
          </DialogContent>
        </Dialog>
      </motion.div>
    </motion.div>
  );
}